﻿#include "mergedialog.h"

#include "mygraphicsview.h"
#include "ui_mergedialog.h"

#include <QFileDialog>
#include <QTextDocument>
#include <QPrinter>
#include <QStandardPaths>
#include <QColorDialog>

const QString TIP = QStringLiteral(" (注:ALt+鼠标中键可缩放图片,鼠标左键按住可拖动图片,选中文本后可拖动文本，Delete键可删除选中文本)");

MergeDialog::MergeDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::MergeDialog)
{
    ui->setupUi(this);

    this->setWindowTitle(QStringLiteral("合并预览"));

    setWindowFlags(Qt::Dialog | Qt::WindowCloseButtonHint | Qt::MSWindowsFixedSizeDialogHint);

    m_scene = new QGraphicsScene(this);

    ui->graphicsView->setScene(m_scene);
    ui->graphicsView->setBackgroundBrush(QBrush(QColor(200,200,200)));

    ui->label->setText(TIP);
    ui->pb_select->setShortcut(QKeySequence("v"));

    ui->pb_undo->setEnabled(false);

    ui->graphicsView->setPenSize(ui->spinBox->value());

    connect(ui->graphicsView,&MyGraphicsView::canUndoChanged,this,[=](bool b){
        ui->pb_undo->setEnabled(b);
    });

//    connect(ui->graphicsView,&MyGraphicsView::doubleClickedItem,this,[=](QGraphicsItem* item){
//        if(item){
//            QGraphicsTextItem * txtItem = static_cast<QGraphicsTextItem*>(item);
//            if(txtItem) {
//                if(m_textSettingDlg->exec() == QDialog::Accepted) {
//                    auto vType = m_textSettingDlg->VType();
//                    auto hType = m_textSettingDlg->HType();
//                    QPoint pos = m_textSettingDlg->point();
//                    auto content = m_textSettingDlg->text();
//                    auto font = m_textSettingDlg->textFont();
//                    auto color = m_textSettingDlg->color();

//                    txtItem->setDefaultTextColor(color);
//                    txtItem->setFont(font);
//                    txtItem->setPlainText(content);

//                    configTextItem(hType, pos, vType, txtItem);
//                }
//            }
//        }
//    });
}

MergeDialog::~MergeDialog()
{
    delete ui;
}

void MergeDialog::setInfoTip()
{
    QString str;
    if(m_item){
        str += QStringLiteral(" 尺寸:%1 * %2").arg(m_size.width()).arg(m_size.height());
    }
    ui->label->setText(str + TIP );
}

void MergeDialog::setImage(const QImage& img)
{
    if(img.isNull()){
        return;
    }

    m_image = img;

    m_scene->clear();
    m_item = nullptr;

    m_size = img.size();
    m_item = m_scene->addPixmap(QPixmap::fromImage(img));
    m_item->setFlag(QGraphicsItem::ItemIsSelectable,false);
    m_scene->setSceneRect(0,0,m_size.width(),m_size.height());

    QPen pen;
    pen.setStyle(Qt::DotLine);
    pen.setColor(Qt::lightGray);
    pen.setWidth(1);

    m_centerLine = m_scene->addLine(QLineF(QPointF(m_size.width()/2,0),QPointF(m_size.width()/2,m_size.height())),pen);
    m_centerLine->setFlag(QGraphicsItem::ItemIsMovable,false);
    m_centerLine->setFlag(QGraphicsItem::ItemIsSelectable,false);
    m_centerLine->setFlag(QGraphicsItem::ItemIsFocusable,false);
    m_centerLine->setZValue(1000);

    ui->graphicsView->centerOn(m_item);
    ui->graphicsView->fitInView(m_scene->sceneRect(),Qt::KeepAspectRatio);

    setInfoTip();
}

void MergeDialog::configTextItem(CBType hType, QPoint pos, CBType vType, QGraphicsTextItem* txtItem)
{
    switch (vType) {
    case V_TOP:
        pos.setY(0);
        break;
    case V_CENTER:
        pos.setY(m_scene->height()/2 - txtItem->boundingRect().height()/2);
        break;
    case V_BOTTOM:
        pos.setY(m_scene->height() - txtItem->boundingRect().height());
        break;
    default:
        break;
    }

    switch (hType) {
    case H_LEFT:
        pos.setX(0);
        break;
    case H_CENTER:
        pos.setX(m_scene->width()/2-txtItem->boundingRect().width()/2);
        break;
    case H_RIGHT:
        pos.setX(m_scene->width() - txtItem->boundingRect().width());
        break;
    default:
        break;
    }

    txtItem->setPos(pos);
}

QImage MergeDialog::render()
{
    QImage image(m_image.size(),QImage::Format_RGB32);
    QPainter painter(&image);
    if(m_centerLine) {
        m_centerLine->setVisible(false);
    }
    m_scene->render(&painter);   //关键函数
    painter.end();
    if(m_centerLine) {
        m_centerLine->setVisible(true);
    }
    return image;

//    QList<QGraphicsItem *> items = m_scene->items();
//    QImage result_image_v = m_image;
//    QPainter painter;
//    painter.setRenderHint(QPainter::Antialiasing, true);
//    painter.begin(&result_image_v);

//    foreach(auto item,items) {
//        if(item && item != m_item && (item->flags() & QGraphicsItem::ItemIsSelectable)){
//            QGraphicsTextItem* textItem = static_cast< QGraphicsTextItem*>(item);
//            auto font = textItem->font();
//            auto txt = textItem->toPlainText();
//            auto pos = textItem->pos();
//            auto color = textItem->defaultTextColor();

//            QFontMetrics fm(font,&result_image_v);

//            painter.save();
//            painter.setPen(color);
//            painter.setFont(font);
//            painter.drawText(QPointF(pos.x(),pos.y()+textItem->document()->size().height() - fm.leading() - fm.descent()),txt);
//            painter.restore();
//        }
//    }

//    painter.end();

//    return result_image_v;
}

void MergeDialog::original()
{
    ui->graphicsView->setTransformationAnchor(QGraphicsView::AnchorViewCenter);
    QMatrix q;
    q.setMatrix(1,ui->graphicsView->matrix().m12(),ui->graphicsView->matrix().m21(),1,ui->graphicsView->matrix().dx(),ui->graphicsView->matrix().dy());
    ui->graphicsView->setMatrix(q,false);
}

void MergeDialog::keyPressEvent(QKeyEvent *event)
{
    auto key = event->key();
    if(key == Qt::Key_Delete) {
        QList<QGraphicsItem *> items = m_scene->selectedItems();
        foreach(auto item,items) {
            if(item){
                m_scene->removeItem(item);
            }
        }
    }
}

void MergeDialog::image2PDF(const QImage& img,QString pdfPath) {
    QPrinter printer_pdf(QPrinter::HighResolution);
    printer_pdf.setPageSize(QPrinter::A4);  //设置纸张大小为A4
    printer_pdf.setOutputFormat(QPrinter::PdfFormat);  //设置输出格式为pdf
    printer_pdf.setOutputFileName(pdfPath);   //设置输出路径

    QPainter painter_pixmap;
    painter_pixmap.begin(&printer_pdf);
    QRect rect = painter_pixmap.viewport();
    int multiple = rect.width()/img.width();
    painter_pixmap.scale(multiple, multiple); //将图像(所有要画的东西)在pdf上放大multiple-1倍
    painter_pixmap.drawImage(0, 0, img);  //画图
    painter_pixmap.end();
}

//#include "Screenshot/screenshot.h"
//void MergeDialog::on_pushButton_4_clicked()
//{
//    QString tmp = QStandardPaths::writableLocation(QStandardPaths::TempLocation);

//    QString path  = tmp + "/songhuan_tool.png";
//    QImage result_image_v = render();
//    result_image_v.save(path);

//    if (!path.isEmpty()) {
//        static QObject* imageEdit = nullptr;
//        if(imageEdit){
//            QMetaObject::invokeMethod(imageEdit,"cancel",Qt::DirectConnection);
//        }

//        ImageEditCB cb;
//        cb.forwordCB = [=](QPixmap img){
//            //qDebug() << "forwordCB";

//            setImage(img.toImage());
//        };

//        cb.finishCB = [=](int code){
//            if(code == 0){

//            }

//            imageEdit = nullptr;
//        };

//        imageEdit = startEdit(path,cb);
//    }
//}

void MergeDialog::on_pb_select_clicked()
{
    ui->graphicsView->setMode(MyGraphicsView::Select);
}

void MergeDialog::on_pb_line_clicked()
{
    ui->graphicsView->setMode(MyGraphicsView::DrawStraightLine);
}

void MergeDialog::on_pb_rect_clicked()
{
    ui->graphicsView->setMode(MyGraphicsView::DrawRect);
}

void MergeDialog::on_pb_round_clicked()
{
    ui->graphicsView->setMode(MyGraphicsView::DrawRound);
}

void MergeDialog::on_pb_text_clicked()
{
    ui->graphicsView->setMode(MyGraphicsView::DrawText);
}

void MergeDialog::on_pb_arrow_clicked()
{
    ui->graphicsView->setMode(MyGraphicsView::DrawArrow);
}

void MergeDialog::on_pb_arrow2_clicked()
{
    ui->graphicsView->setMode(MyGraphicsView::DrawArrow2);
}

void MergeDialog::on_pb_draw_clicked()
{
    ui->graphicsView->setMode(MyGraphicsView::DrawLine);
}

void MergeDialog::on_spinBox_valueChanged(int arg1)
{
    ui->graphicsView->setPenSize(arg1);
}

void MergeDialog::on_pb_color_clicked()
{
    auto color = QColorDialog::getColor(ui->graphicsView->penColor(),this);
    if(!color.isValid()) {
        return;
    }

    ui->graphicsView->setPenColor(color);

    auto style = QString("background-color: rgb(%1, %2, %3);border:none;")
            .arg(color.red())
            .arg(color.green())
            .arg(color.blue());
    ui->pb_color->setStyleSheet(style);
}

void MergeDialog::on_pb_origin_clicked()
{
    original();
}

void MergeDialog::on_pb_save_clicked()
{
    QImage result_image_v = render();

    QString path =  QFileDialog::getSaveFileName(this,"select save file",QString(),"Images (*.jpg *.png)");
    if(!path.isEmpty()) {
        result_image_v.save(path,Q_NULLPTR,100);
    }
}

void MergeDialog::on_pb_export_clicked()
{
    QImage result_image_v = render();

    QString path =  QFileDialog::getSaveFileName(this,"select save file",QString(),"Pdf (*.pdf)");
    if(!path.isEmpty()) {
        image2PDF(result_image_v,path);
    }
}

void MergeDialog::on_pb_undo_clicked()
{
    ui->graphicsView->undo();
}
